// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const TcbRouter = require('tcb-router')
const db = cloud.database()
const blogCollection = db.collection('blog')
const commentCollection = db.collection('blog-comment')

// 云函数入口函数
exports.main = async (event, context) => {
  const app = new TcbRouter({ event })
  // 点击搜索，根据关键字查询博客的云函数
  app.router('list', async (ctx,next) => {
    const keyword = event.keyword
    let w ={}
    if (keyword.trim() != '') {
      w = {
        content: db.RegExp({
          regexp: keyword,// 数据库的正则表达式用法，可以使用变量来匹配
          options: 'i'
        })
      }
    }
    ctx.body = await blogCollection
    .where(w)
    .skip(event.start)
    .limit(event.count)
    .orderBy('createTime','desc')
    .get()
    .then(res => {
      return res
    })
  })

  // 获取博客详情及博客评论
  app.router('detail', async (ctx,next) =>{
    const blogId = event.blogId
    // 博客详情查询
    let blogDetail = await blogCollection
    .where({_id: blogId})
    .get()
    .then(res => res.data)
    
    // 博客评论查询
    const commentResult =await commentCollection.count()
    const total = commentResult.total
    
    
    let commentList = {
      data:[]
    }
    if (total>0) {
      let batchTimes = Math.ceil(total / 100)
      let tasks = []
      for (let i = 0; i < batchTimes; i++) {
        let promise = commentCollection
        .skip(i * 100)
        .limit(100)
        .where({blogId})
        .orderBy('createTime','desc')
        .get()
        tasks.push(promise)
      }
      if(tasks.length > 0) {
        commentList = (await Promise.all(tasks)).reduce(
          (acc,cur) => {
            return {
              data: acc.data.concat(cur.data)
            }
        })
      }
    }
    ctx.body = {
      blogDetail,
      commentList
    }
  })
  return app.serve()
}